package com.jkgl.socket;

import com.alibaba.fastjson2.JSON;
import com.jkgl.common.core.domain.model.LoginUser;
import com.jkgl.common.utils.spring.SpringUtils;
import com.jkgl.entity.UserInfoDayEntity;
import com.jkgl.model.socket.MessageVO;
import com.jkgl.service.UserInfoDayService;
import com.jkgl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import com.jkgl.framework.web.service.TokenService;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/userConn")
public class NoticeSocket {

    private Session session;
    private TokenService tokenService;
    private ISysUserService userService;
    private UserInfoDayService dayService;

    public NoticeSocket(){
        this.tokenService = SpringUtils.getBean(TokenService.class);
        this.userService = SpringUtils.getBean(ISysUserService.class);
        this.dayService = SpringUtils.getBean(UserInfoDayService.class);
    }

//    用户与session关联
    private final static ConcurrentHashMap<Long,Session> curren = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) throws IOException {
        this.session = session;
        LoginUser loginUser = tokenService.getLoginUser(session.getQueryString().substring(session.getQueryString().indexOf("=") + 1));
        if(loginUser == null){
            onClose();
            return;
        }
        curren.put(loginUser.getUserId(),session);
        checkData(loginUser);
    }

    private void checkData(LoginUser loginUser) throws IOException {
        List<UserInfoDayEntity> userInfoToday = dayService.getUserInfoToday(loginUser.getUserId());
        if(userInfoToday.isEmpty()||userInfoToday.get(0)==null){
            curren.get(loginUser.getUserId()).getBasicRemote().sendText(
                    JSON.toJSONString(MessageVO.builder()
                            .title("今日信息提醒")
                            .context("今日份信息还未及时登记")
                            .build())
            );
            return;
        }
        if(userInfoToday.get(0).getCreateTime().isEqual(LocalDate.now())){
            curren.get(loginUser.getUserId()).getBasicRemote().sendText(
                    JSON.toJSONString(MessageVO.builder()
                            .title("今日信息提醒")
                            .context("今日份日报请注意查收")
                            .build())
            );
        }else{
            curren.get(loginUser.getUserId()).getBasicRemote().sendText(
                    JSON.toJSONString(MessageVO.builder()
                            .title("今日信息提醒")
                            .context("今日份信息还未及时登记")
                            .build())
            );
        }
    }

    public void sendMessage(MessageVO vo){
        System.out.println(vo.toString());
        curren.forEach((k,v) -> {
            System.out.println(k);
            System.out.println(v);
            try {
                v.getBasicRemote().sendText(JSON.toJSONString(vo));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    //Authorization
    @OnClose
    public void onClose() {
        log.info("WebSocket连接关闭");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自SessionId:{}的消息:{}", session.getId(), message);
//        session.getBasicRemote().sendText();
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("Session:{}的WebSocket发生错误", session.getId(), error);
    }

    public Session getSession() {
        return session;
    }

    public String getSessionId() {
        return session.getId();
    }


    public static void main(String[] args) {
        curren.forEach((key,value) ->{
            try {
                System.out.println(value);
                value.getBasicRemote().sendText("1111");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

}